package com.candy.candysocket.netty;

import com.gitee.candy.dateTime.DateUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2024/7/19 8:46
 * @Description 描述
 */
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    private AtomicInteger lossConnectCount = new AtomicInteger(0);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println(DateUtil.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss") + "已经5秒未收到客户端的消息了！");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                lossConnectCount.getAndIncrement();
                if (lossConnectCount.get() > 2) {
                    System.out.println("关闭这个不活跃通道！");
                    ctx.channel().close();
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        lossConnectCount = new AtomicInteger(0);
        System.out.println(DateUtil.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss") + "client says: " + msg.toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接断开时被调用
        System.out.println("Connection lost, attempting reconnection...");
//        reconnect(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}